package week07.data_obs3;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangxiaokun on 2018/3/13.
 */
public abstract class Subject {
    /**
     * 观察者列表
     */
    List<Observer> list = new ArrayList<>();

    /**
     * 注册观察者
     * @param observer
     */
    public void attach(Observer observer) {
        if (observer == null) {
            throw new NullPointerException();
        }
        //没注册过
        if (!list.contains(observer)) {
            list.add(observer);
        }
    }

    /**
     * 删除指定观察者
     * @param observer
     */
    public void detach(Observer observer) {
        if (observer == null) {
            throw new NullPointerException();
        }
        if (list.contains(observer)) {
            list.remove(observer);
        }
    }

    /**
     * 通知所有注册的观察者
     * @param newState
     */
    public void nodifyObservers(String newState) {
        for(Observer observer : list) {
            observer.update(newState);
        }
    }

}
